package com.toutou.base.bindhelper

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
import com.toutou.base.util.hideSoftKeyboard

class RecyclerBDAdapter {
    companion object{
        @SuppressLint("ClickableViewAccessibility")
        @JvmStatic
        @BindingAdapter(
            value = ["adapter", "isNotLinearLayoutManager", "isHorizontal", "customLayoutManager","autoMissKeyboardForEditText"],
            requireAll = false
        )
        fun recyclerViewAdapter(
            recyclerView: RecyclerView,
            adapter: RecyclerView.Adapter<*>?,
            isNotLinearLayoutManager: Boolean,
            isHorizontal: Boolean,
            customLayoutManager: RecyclerView.LayoutManager?,
            autoMissKeyboardForEditText: View?
        ) {
            recyclerView.itemAnimator = null
            if (!isNotLinearLayoutManager) {
                val manager = LinearLayoutManager(recyclerView.context)
                if (isHorizontal) {
                    manager.orientation = RecyclerView.HORIZONTAL
                }
                recyclerView.layoutManager = manager
            } else {
                recyclerView.layoutManager = customLayoutManager
            }

            if (adapter != null) {
                recyclerView.adapter = adapter
            }

//            recyclerView在试图滚动的时候，隐藏软键盘
            if (autoMissKeyboardForEditText != null) {
                recyclerView.addOnItemTouchListener(object : OnItemTouchListener{
                    override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                        hideSoftKeyboard(rv.context, autoMissKeyboardForEditText)
                        return false
                    }

                    override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                    }

                    override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
                    }
                })
            }
        }
    }
}